package JaggSoft;

import JaggSoft.Utilidades.*;
import java.awt.*;
import java.text.SimpleDateFormat;
import java.util.Date;
import javax.swing.*;
//import javax.swing.table.DefaultTableModel;
import net.sourceforge.jdatepicker.impl.JDatePickerImpl;

public class Productos extends javax.swing.JInternalFrame {
    private JDatePickerImpl selector_fecha;
    private JCheckBox jchkFechaVencimiento;
    private boolean nuevo;
    public Productos() {
        initComponents();
        this.setLocation(new Point(70,0));
        jchkFechaVencimiento=new JCheckBox();
        jchkFechaVencimiento.setSelected(false);
        jchkFechaVencimiento.setToolTipText("Incluir Fecha de Vencimiento");
        Component comp[]={jchkFechaVencimiento};
        selector_fecha=Util.ColocarSelectorFecha(jpFechaVencimiento,null,comp);
        /*CargarMarcas();
        CargarProveedores();*/
        BloquearControles(true);
        BloquearTexto(true);
        CargarBodegas();
        Limpiar();
        jbtnBuscar.setVisible(false);
        jbtnCambiarDetalle.setVisible(false);
        this.setSize(this.getWidth(),600);
/*        Util.OcultarColumna(jtblMarcaProveedor,0);
        Util.OcultarColumna(jtblMarcaProveedor,2);
        Util.ColocarEditorCelda(jtblMarcaProveedor,"0",Long.class);
        Util.EstablecerEliminadorFila(jtblMarcaProveedor);*/
    }
    private void CargarBodegas(){
        String columnas[]={"ID","Bodega","Cantidad","Ubicación"};
        boolean cols_edit[]={false,false,true,false};
        /*Util.CargarTablaEditable(jtblDistribucion,"SELECT id_bodega,nombre,0 AS cantidad,ubicacion FROM bodega",columnas,cols_edit);
        Util.OcultarColumna(jtblDistribucion,0);*/
    }
    private void BloquearControles(boolean estado){
        jtbtnHabilitarBusqueda.setSelected(false);
        jpInventario.setVisible(false);
        /*jpMarcasDistribucion.setVisible(true);
        jbtnAgregarMarcaProveedor.setEnabled(!estado);*/
        
        jbtnNuevo.setEnabled(estado);
        jbtnGuardar.setEnabled(!estado);
        jbtnModificar.setEnabled(estado);
        jbtnEliminar.setEnabled(estado);
        jbtnCancelar.setEnabled(!estado);
        //jbtnDistribuir.setEnabled(!estado);
    }
    private void BloquearTexto(boolean estado){
        jtfNombre.setEditable(!estado);
        jtfUnidadMedida.setEditable(!estado);
        jtfPrecioUnidad.setEditable(!estado);
        jtaDetalle.setEditable(!estado);
        /*jcbMarcas.setEnabled(!estado);
        jcbProveedores.setEnabled(!estado);*/
        jtfExistencia.setEditable(!estado);
        jtfCantidadMinima.setEditable(!estado);
        selector_fecha.getComponent(1).setEnabled(!estado);
        /*jtblMarcaProveedor.setEnabled(!estado);
        jtblDistribucion.setEnabled(!estado);*/
    }
    private void Limpiar(){
        jtfId.setText(null);
        jtfNombre.setText(null);
        jtaDetalle.setText(null);
        jtfUnidadMedida.setText(null);
        jtfPrecioUnidad.setText(null);
        jtfExistencia.setText(null);
        jtfCantidadMinima.setText(null);
        /*jcbMarcas.setSelectedIndex(-1);
        jcbProveedores.setSelectedIndex(-1);
        while(jtblMarcaProveedor.getRowCount()>0)
            ((DefaultTableModel)jtblMarcaProveedor.getModel()).removeRow(0);*/
    }
    /*private void CargarMarcas(){
        jcbMarcas.removeAllItems();
        String columnas[]={"id","marca"};
        Util.CargarJComboBox(jcbMarcas,"SELECT id_marca,descripcion FROM marca",columnas);
    }
    private void CargarProveedores(){
        jcbProveedores.removeAllItems();
        String columnas[]={"id","nombre"};
        Util.CargarJComboBox(jcbProveedores,"SELECT id_proveedor,nombre FROM proveedor",columnas);
    }*/
    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {

        jpProducto = new javax.swing.JPanel();
        jLabel1 = new javax.swing.JLabel();
        jtfNombre = new javax.swing.JTextField();
        jtfId = new javax.swing.JTextField();
        jLabel10 = new javax.swing.JLabel();
        jLabel9 = new javax.swing.JLabel();
        jLabel6 = new javax.swing.JLabel();
        jtfUnidadMedida = new javax.swing.JTextField();
        jLabel7 = new javax.swing.JLabel();
        jtfPrecioUnidad = new javax.swing.JTextField();
        jLabel8 = new javax.swing.JLabel();
        jScrollPane3 = new javax.swing.JScrollPane();
        jtaDetalle = new javax.swing.JTextArea();
        jpFechaVencimiento = new javax.swing.JPanel();
        jLabel5 = new javax.swing.JLabel();
        jtfExistencia = new javax.swing.JTextField();
        jpAccion = new javax.swing.JPanel();
        jbtnCancelar = new javax.swing.JButton();
        jbtnEliminar = new javax.swing.JButton();
        jbtnModificar = new javax.swing.JButton();
        jbtnGuardar = new javax.swing.JButton();
        jbtnNuevo = new javax.swing.JButton();
        jtbtnHabilitarBusqueda = new javax.swing.JToggleButton();
        jbtnBuscar = new javax.swing.JButton();
        jbtnCambiarDetalle = new javax.swing.JButton();
        jLabel11 = new javax.swing.JLabel();
        jtfCantidadMinima = new javax.swing.JTextField();
        jpInventario = new javax.swing.JPanel();
        jScrollPane4 = new javax.swing.JScrollPane();
        jtblProductos = new javax.swing.JTable();

        setClosable(true);
        setMaximizable(true);
        setTitle("Administración de Productos");
        addInternalFrameListener(new javax.swing.event.InternalFrameListener() {
            public void internalFrameActivated(javax.swing.event.InternalFrameEvent evt) {
            }
            public void internalFrameDeactivated(javax.swing.event.InternalFrameEvent evt) {
            }
            public void internalFrameDeiconified(javax.swing.event.InternalFrameEvent evt) {
            }
            public void internalFrameIconified(javax.swing.event.InternalFrameEvent evt) {
            }
            public void internalFrameClosed(javax.swing.event.InternalFrameEvent evt) {
            }
            public void internalFrameClosing(javax.swing.event.InternalFrameEvent evt) {
                formInternalFrameClosing(evt);
            }
            public void internalFrameOpened(javax.swing.event.InternalFrameEvent evt) {
            }
        });

        jpProducto.setBorder(javax.swing.BorderFactory.createTitledBorder("Producto"));

        jLabel1.setText("Nombre:");

        jtfNombre.setToolTipText("Nombre del Producto");

        jtfId.setEditable(false);

        jLabel10.setText("Código:");

        jLabel9.setText("Detalle:");

        jLabel6.setText("Unidad de Medida:");

        jLabel7.setText("Precio de Unidad de Medida:");

        jtfPrecioUnidad.addKeyListener(new java.awt.event.KeyAdapter() {
            public void keyTyped(java.awt.event.KeyEvent evt) {
                jtfPrecioUnidadKeyTyped(evt);
            }
        });

        jLabel8.setText("Fecha de Vencimiento:");

        jtaDetalle.setColumns(20);
        jtaDetalle.setRows(5);
        jScrollPane3.setViewportView(jtaDetalle);

        javax.swing.GroupLayout jpFechaVencimientoLayout = new javax.swing.GroupLayout(jpFechaVencimiento);
        jpFechaVencimiento.setLayout(jpFechaVencimientoLayout);
        jpFechaVencimientoLayout.setHorizontalGroup(
            jpFechaVencimientoLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGap(0, 105, Short.MAX_VALUE)
        );
        jpFechaVencimientoLayout.setVerticalGroup(
            jpFechaVencimientoLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGap(0, 14, Short.MAX_VALUE)
        );

        jLabel5.setText("Existencia:");

        jtfExistencia.addKeyListener(new java.awt.event.KeyAdapter() {
            public void keyTyped(java.awt.event.KeyEvent evt) {
                jtfExistenciaKeyTyped(evt);
            }
        });

        jpAccion.setBorder(javax.swing.BorderFactory.createTitledBorder("Acciones"));

        jbtnCancelar.setIcon(new javax.swing.ImageIcon(getClass().getResource("/Recursos/accion_cancelar.png"))); // NOI18N
        jbtnCancelar.setToolTipText("Cancelar");
        jbtnCancelar.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jbtnCancelarActionPerformed(evt);
            }
        });

        jbtnEliminar.setIcon(new javax.swing.ImageIcon(getClass().getResource("/Recursos/accion_eliminar.png"))); // NOI18N
        jbtnEliminar.setToolTipText("Eliminar");
        jbtnEliminar.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jbtnEliminarActionPerformed(evt);
            }
        });

        jbtnModificar.setIcon(new javax.swing.ImageIcon(getClass().getResource("/Recursos/accion_modificar.png"))); // NOI18N
        jbtnModificar.setToolTipText("Modificar");
        jbtnModificar.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jbtnModificarActionPerformed(evt);
            }
        });

        jbtnGuardar.setIcon(new javax.swing.ImageIcon(getClass().getResource("/Recursos/accion_guardar.png"))); // NOI18N
        jbtnGuardar.setToolTipText("Guardar");
        jbtnGuardar.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jbtnGuardarActionPerformed(evt);
            }
        });

        jbtnNuevo.setIcon(new javax.swing.ImageIcon(getClass().getResource("/Recursos/accion_nuevo.png"))); // NOI18N
        jbtnNuevo.setToolTipText("Nuevo");
        jbtnNuevo.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jbtnNuevoActionPerformed(evt);
            }
        });

        jtbtnHabilitarBusqueda.setIcon(new javax.swing.ImageIcon(getClass().getResource("/Recursos/habilitar_busqueda.png"))); // NOI18N
        jtbtnHabilitarBusqueda.setToolTipText("Habilitar Busqueda");
        jtbtnHabilitarBusqueda.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jtbtnHabilitarBusquedaActionPerformed(evt);
            }
        });

        jbtnBuscar.setIcon(new javax.swing.ImageIcon(getClass().getResource("/Recursos/accion_buscar.png"))); // NOI18N
        jbtnBuscar.setToolTipText("Buscar");
        jbtnBuscar.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jbtnBuscarActionPerformed(evt);
            }
        });

        jbtnCambiarDetalle.setIcon(new javax.swing.ImageIcon(getClass().getResource("/Recursos/ver_detalle.png"))); // NOI18N
        jbtnCambiarDetalle.setToolTipText("Cambiar Detalle");
        jbtnCambiarDetalle.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jbtnCambiarDetalleActionPerformed(evt);
            }
        });

        javax.swing.GroupLayout jpAccionLayout = new javax.swing.GroupLayout(jpAccion);
        jpAccion.setLayout(jpAccionLayout);
        jpAccionLayout.setHorizontalGroup(
            jpAccionLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(jpAccionLayout.createSequentialGroup()
                .addGroup(jpAccionLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addGroup(jpAccionLayout.createSequentialGroup()
                        .addComponent(jbtnNuevo, javax.swing.GroupLayout.PREFERRED_SIZE, 37, javax.swing.GroupLayout.PREFERRED_SIZE)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addComponent(jtbtnHabilitarBusqueda, javax.swing.GroupLayout.PREFERRED_SIZE, 38, javax.swing.GroupLayout.PREFERRED_SIZE)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addComponent(jbtnBuscar, javax.swing.GroupLayout.PREFERRED_SIZE, 37, javax.swing.GroupLayout.PREFERRED_SIZE)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addComponent(jbtnCambiarDetalle, javax.swing.GroupLayout.PREFERRED_SIZE, 37, javax.swing.GroupLayout.PREFERRED_SIZE))
                    .addGroup(jpAccionLayout.createSequentialGroup()
                        .addComponent(jbtnGuardar, javax.swing.GroupLayout.PREFERRED_SIZE, 37, javax.swing.GroupLayout.PREFERRED_SIZE)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addComponent(jbtnModificar, javax.swing.GroupLayout.PREFERRED_SIZE, 37, javax.swing.GroupLayout.PREFERRED_SIZE)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addComponent(jbtnEliminar, javax.swing.GroupLayout.PREFERRED_SIZE, 37, javax.swing.GroupLayout.PREFERRED_SIZE)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addComponent(jbtnCancelar, javax.swing.GroupLayout.PREFERRED_SIZE, 37, javax.swing.GroupLayout.PREFERRED_SIZE)))
                .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
        );
        jpAccionLayout.setVerticalGroup(
            jpAccionLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(jpAccionLayout.createSequentialGroup()
                .addGroup(jpAccionLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addComponent(jtbtnHabilitarBusqueda, javax.swing.GroupLayout.PREFERRED_SIZE, 37, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(jbtnBuscar, javax.swing.GroupLayout.PREFERRED_SIZE, 37, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(jbtnNuevo, javax.swing.GroupLayout.PREFERRED_SIZE, 37, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(jbtnCambiarDetalle, javax.swing.GroupLayout.PREFERRED_SIZE, 37, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                .addGroup(jpAccionLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addComponent(jbtnCancelar, javax.swing.GroupLayout.PREFERRED_SIZE, 37, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(jbtnGuardar, javax.swing.GroupLayout.PREFERRED_SIZE, 37, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(jbtnModificar, javax.swing.GroupLayout.PREFERRED_SIZE, 37, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(jbtnEliminar, javax.swing.GroupLayout.PREFERRED_SIZE, 37, javax.swing.GroupLayout.PREFERRED_SIZE)))
        );

        jLabel11.setText("Cantidad Mínima:");

        jtfCantidadMinima.addKeyListener(new java.awt.event.KeyAdapter() {
            public void keyTyped(java.awt.event.KeyEvent evt) {
                jtfCantidadMinimaKeyTyped(evt);
            }
        });

        javax.swing.GroupLayout jpProductoLayout = new javax.swing.GroupLayout(jpProducto);
        jpProducto.setLayout(jpProductoLayout);
        jpProductoLayout.setHorizontalGroup(
            jpProductoLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(jpProductoLayout.createSequentialGroup()
                .addGroup(jpProductoLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addGroup(jpProductoLayout.createSequentialGroup()
                        .addComponent(jLabel10, javax.swing.GroupLayout.PREFERRED_SIZE, 53, javax.swing.GroupLayout.PREFERRED_SIZE)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addComponent(jtfId, javax.swing.GroupLayout.PREFERRED_SIZE, 80, javax.swing.GroupLayout.PREFERRED_SIZE)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                        .addComponent(jLabel1, javax.swing.GroupLayout.PREFERRED_SIZE, 53, javax.swing.GroupLayout.PREFERRED_SIZE)
                        .addGap(4, 4, 4)
                        .addComponent(jtfNombre, javax.swing.GroupLayout.PREFERRED_SIZE, 224, javax.swing.GroupLayout.PREFERRED_SIZE)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                        .addComponent(jLabel9))
                    .addGroup(jpProductoLayout.createSequentialGroup()
                        .addGroup(jpProductoLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                            .addGroup(jpProductoLayout.createSequentialGroup()
                                .addComponent(jLabel6)
                                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                                .addComponent(jtfUnidadMedida, javax.swing.GroupLayout.PREFERRED_SIZE, 140, javax.swing.GroupLayout.PREFERRED_SIZE)
                                .addGap(18, 18, 18)
                                .addComponent(jLabel7)
                                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                                .addComponent(jtfPrecioUnidad, javax.swing.GroupLayout.PREFERRED_SIZE, 129, javax.swing.GroupLayout.PREFERRED_SIZE))
                            .addGroup(jpProductoLayout.createSequentialGroup()
                                .addGap(246, 246, 246)
                                .addComponent(jLabel11, javax.swing.GroupLayout.PREFERRED_SIZE, 110, javax.swing.GroupLayout.PREFERRED_SIZE)
                                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                                .addComponent(jtfCantidadMinima, javax.swing.GroupLayout.PREFERRED_SIZE, 117, javax.swing.GroupLayout.PREFERRED_SIZE))
                            .addGroup(jpProductoLayout.createSequentialGroup()
                                .addComponent(jLabel5, javax.swing.GroupLayout.PREFERRED_SIZE, 59, javax.swing.GroupLayout.PREFERRED_SIZE)
                                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                                .addComponent(jtfExistencia, javax.swing.GroupLayout.PREFERRED_SIZE, 117, javax.swing.GroupLayout.PREFERRED_SIZE))
                            .addGroup(jpProductoLayout.createSequentialGroup()
                                .addComponent(jLabel8)
                                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                                .addComponent(jpFechaVencimiento, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)))
                        .addGap(0, 7, Short.MAX_VALUE)))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addGroup(jpProductoLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addComponent(jScrollPane3, javax.swing.GroupLayout.PREFERRED_SIZE, 280, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, jpProductoLayout.createSequentialGroup()
                        .addComponent(jpAccion, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                        .addGap(42, 42, 42)))
                .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
        );
        jpProductoLayout.setVerticalGroup(
            jpProductoLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(jpProductoLayout.createSequentialGroup()
                .addGroup(jpProductoLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addGroup(jpProductoLayout.createSequentialGroup()
                        .addContainerGap()
                        .addGroup(jpProductoLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                            .addGroup(jpProductoLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                                .addComponent(jLabel1)
                                .addComponent(jtfNombre, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                                .addComponent(jLabel9))
                            .addGroup(jpProductoLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                                .addComponent(jLabel10)
                                .addComponent(jtfId, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)))
                        .addGap(17, 17, 17)
                        .addGroup(jpProductoLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                            .addComponent(jLabel6)
                            .addComponent(jtfUnidadMedida, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                            .addComponent(jLabel7)
                            .addComponent(jtfPrecioUnidad, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)))
                    .addComponent(jScrollPane3, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addGroup(jpProductoLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addGroup(jpProductoLayout.createSequentialGroup()
                        .addGap(9, 9, 9)
                        .addGroup(jpProductoLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false)
                            .addComponent(jLabel8, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                            .addComponent(jpFechaVencimiento, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                        .addGap(18, 18, 18)
                        .addGroup(jpProductoLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                            .addComponent(jtfCantidadMinima, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                            .addComponent(jLabel5)
                            .addComponent(jtfExistencia, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                            .addComponent(jLabel11)))
                    .addGroup(jpProductoLayout.createSequentialGroup()
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addComponent(jpAccion, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))))
        );

        jpInventario.setBorder(javax.swing.BorderFactory.createTitledBorder("Inventario"));

        jtblProductos.addMouseListener(new java.awt.event.MouseAdapter() {
            public void mouseClicked(java.awt.event.MouseEvent evt) {
                jtblProductosMouseClicked(evt);
            }
        });
        jScrollPane4.setViewportView(jtblProductos);

        javax.swing.GroupLayout jpInventarioLayout = new javax.swing.GroupLayout(jpInventario);
        jpInventario.setLayout(jpInventarioLayout);
        jpInventarioLayout.setHorizontalGroup(
            jpInventarioLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(jpInventarioLayout.createSequentialGroup()
                .addContainerGap()
                .addComponent(jScrollPane4)
                .addContainerGap())
        );
        jpInventarioLayout.setVerticalGroup(
            jpInventarioLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(jpInventarioLayout.createSequentialGroup()
                .addComponent(jScrollPane4, javax.swing.GroupLayout.PREFERRED_SIZE, 169, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addGap(0, 0, Short.MAX_VALUE))
        );

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
        getContentPane().setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addGroup(layout.createSequentialGroup()
                        .addComponent(jpProducto, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                        .addGap(0, 0, Short.MAX_VALUE))
                    .addComponent(jpInventario, javax.swing.GroupLayout.Alignment.TRAILING, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
                .addContainerGap())
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addComponent(jpProducto, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(jpInventario, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
        );

        pack();
    }// </editor-fold>//GEN-END:initComponents
    private String getFiltro(){
        String filtro="";
        Date f=(Date)selector_fecha.getModel().getValue();
        SimpleDateFormat formato=new SimpleDateFormat("yyyy/MM/dd");
        filtro=(jtfNombre.getText().length()>0?" WHERE p.nombre LIKE '"+jtfNombre.getText().replaceAll("'","\'")+"%'":"");
        filtro+=(!jtaDetalle.getText().equals("")?(!filtro.equals("")?" AND":" WHERE")+" i.detalle LIKE '"+jtaDetalle.getText().replaceAll("'","\'")+"%'":"");
        filtro+=(!jtfUnidadMedida.getText().equals("")?(!filtro.equals("")?" AND":" WHERE")+" i.unidad_medida LIKE '"+jtfUnidadMedida.getText().replaceAll("'","\'")+"%'":"");
        filtro+=(!jtfPrecioUnidad.getText().equals("")?(!filtro.equals("")?" AND":" WHERE")+" i.precio_unidad_medida="+jtfPrecioUnidad.getText():"");
        filtro+=(jchkFechaVencimiento.isSelected()?(f!=null?(!filtro.equals("")?" AND":" WHERE")+" p.fecha_vencimiento='"+formato.format(f)+"'":""):"");
        filtro+=(!jtfExistencia.getText().equals("")?(!filtro.equals("")?" AND":" WHERE")+" i.existencia="+jtfExistencia.getText():"");
        filtro+=(!jtfCantidadMinima.getText().equals("")?(!filtro.equals("")?" AND":" WHERE")+" i.cantidad_minima="+jtfCantidadMinima.getText():"");
        return filtro;
    }
    private void formInternalFrameClosing(javax.swing.event.InternalFrameEvent evt) {//GEN-FIRST:event_formInternalFrameClosing
        selector_fecha.hidePopup();
        selector_fecha=null;
    }//GEN-LAST:event_formInternalFrameClosing
    private void jbtnNuevoActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jbtnNuevoActionPerformed
        BloquearControles(false);
        BloquearTexto(false);
        Limpiar();
        nuevo=true;
    }//GEN-LAST:event_jbtnNuevoActionPerformed
    private void jbtnCancelarActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jbtnCancelarActionPerformed
        BloquearControles(true);
        BloquearTexto(true);
        if(jtfId.getText().equals(""))
            Limpiar();
    }//GEN-LAST:event_jbtnCancelarActionPerformed
    private void jbtnGuardarActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jbtnGuardarActionPerformed
        if(ValidarCampos()){
            if(nuevo)
                Guardar();
            else{
                if(!jtfId.getText().equals(""))
                    Actualizar();
                else
                    JOptionPane.showMessageDialog(null,"Para actualizar un producto de inventario primero debe seleccionarse el producto y cargar su información","No ha seleccionado producto",JOptionPane.WARNING_MESSAGE);
            }
            BloquearControles(true);
            BloquearTexto(true);
        }
    }//GEN-LAST:event_jbtnGuardarActionPerformed
    /*private String[] getIdsMarcasProveedores(){
        String ids[]={"","",""};
        for(int i=0;i<jtblMarcaProveedor.getRowCount();i++){
            if(ids[0].equals("")){
                ids[0]=jtblMarcaProveedor.getValueAt(i,0).toString();
                ids[1]=jtblMarcaProveedor.getValueAt(i,2).toString();
                ids[2]=jtblMarcaProveedor.getValueAt(i,4).toString();
            }
            else{
                ids[0]+=","+jtblMarcaProveedor.getValueAt(i,0).toString();
                ids[1]+=","+jtblMarcaProveedor.getValueAt(i,2).toString();
                ids[2]+=","+jtblMarcaProveedor.getValueAt(i,4).toString();
            }
        }
        return ids;
    }*/
    private void Guardar(){
        /*String fecha_vencimiento="NULL,";
        String mar_prov_can[]=getIdsMarcasProveedores();
        if(jchkFechaVencimiento.isSelected()){
            Date fecha=((Date)selector_fecha.getModel().getValue());
            SimpleDateFormat formato=new SimpleDateFormat("yyyy/MM/dd");
            fecha_vencimiento="'"+formato.format(fecha)+"',";
        }
        if(Conexion.EjecutarProcedimientoAlmacenado("CALL AgregarInventario('"+jtfNombre.getText().replace("'","\'")+"',"+fecha_vencimiento
                +jtfExistencia.getText()+",'"+jtaDetalle.getText().replace("'","\'")+"','"+jtfUnidadMedida.getText().replace("'","\'")+"',"
                +jtfCantidadMinima.getText()+","+jtfPrecioUnidad.getText()+",'"+mar_prov_can[0]+"','"+mar_prov_can[1]+"','"
                +mar_prov_can[2]+"');")){
                        JOptionPane.showMessageDialog(null,"¡Producto Agregado!","Producto",JOptionPane.INFORMATION_MESSAGE);
        }
        else
            JOptionPane.showMessageDialog(null,"¡Hubo un error al agregar el producto!","Producto",JOptionPane.ERROR_MESSAGE);*/
    }
    private void Actualizar(){
        /*String fecha_vencimiento="NULL,";
        String mar_prov_can[]=getIdsMarcasProveedores();
        if(jchkFechaVencimiento.isSelected()){
            Date fecha=((Date)selector_fecha.getModel().getValue());
            SimpleDateFormat formato=new SimpleDateFormat("yyyy/MM/dd");
            fecha_vencimiento="'"+formato.format(fecha)+"',";
        }
        if(Conexion.EjecutarProcedimientoAlmacenado("CALL ModificarInventario("+jtfId.getText()+",'"+jtfNombre.getText().replace("'","\'")
                +"',"+fecha_vencimiento+jtfExistencia.getText()+",'"+jtaDetalle.getText().replace("'","\'")+"','"
                +jtfUnidadMedida.getText().replace("'","\'")+"',"+jtfCantidadMinima.getText()+","+jtfPrecioUnidad.getText()+",'"+mar_prov_can[0]
                +"','"+mar_prov_can[1]+"','"+mar_prov_can[2]+"');"))
                    JOptionPane.showMessageDialog(null,"¡Producto Actualizado!","Producto",JOptionPane.INFORMATION_MESSAGE);
        else
            JOptionPane.showMessageDialog(null,"¡Hubo un error al actualizar el producto!","Producto",JOptionPane.ERROR_MESSAGE);*/
    }
    private void Eliminar(String id){
        if(Conexion.EjecutarProcedimientoAlmacenado("CALL EliminarInventario("+id+");"))
            JOptionPane.showMessageDialog(null,"¡Producto Eliminado!","Producto",JOptionPane.INFORMATION_MESSAGE);
        else
            JOptionPane.showMessageDialog(null,"¡Hubo un error al eliminar el producto!","Producto",JOptionPane.ERROR_MESSAGE);
    }
    private boolean ValidarCampos(){
        String msj=null;
        msj=(jtfNombre.getText().equals("")?"Falta ingresar el nombre":"");
        msj+=(jtfUnidadMedida.getText().equals("")?(msj.equals("")?"Falta ingresar la unidad de medida":", la unidad de medida"):"");
        msj+=(jtfPrecioUnidad.getText().equals("")?(msj.equals("")?"Falta ingresar el precio de la unidad de medida":", el precio de la unidad de medida"):"");
        msj+=(jtfExistencia.getText().equals("")?(msj.equals("")?"Falta ingresar la existencia":", la existencia"):"");
        msj+=(jtfCantidadMinima.getText().equals("")?(msj.equals("")?"Falta ingresar la cantidad mínima":", la cantidad mínima"):"");
        /*msj+=(!VerificarSumatoria(Integer.parseInt(jtfExistencia.getText().equals("")?"-1":jtfExistencia.getText()),jtblMarcaProveedor,4)?(msj.equals("")
                ?"Las distribucion de la cantidad del producto respecto a marcas y proveedores no concuerda con la existencia"
                :", no concuerda la cantidad respecto a marcas y proveedores con la existencia"):"");*/
        if(!msj.equals("")) JOptionPane.showMessageDialog(null,msj+".","Falta ingresar algunos campos",JOptionPane.WARNING_MESSAGE);
        return msj.equals("");
    }
    private boolean VerificarSumatoria(int total,JTable tabla,int columna){
        int suma=0;
        try {
            for (int i=0;i<tabla.getRowCount();i++) {
                suma+=Integer.parseInt(tabla.getValueAt(i,columna).toString());
            }
        } catch (Exception ex) { return false; }
        return (suma==total);
    }
    private boolean VerificarMarcaProveedorRepetido(String marca,String proveedor){
        /*for(int i=0;i<jtblMarcaProveedor.getRowCount();i++)
            if(marca.equals(jtblMarcaProveedor.getValueAt(i,0).toString()) && proveedor.equals(jtblMarcaProveedor.getValueAt(i,2).toString()))
                return false;*/
        return true;
    }
    private void jtfPrecioUnidadKeyTyped(java.awt.event.KeyEvent evt) {//GEN-FIRST:event_jtfPrecioUnidadKeyTyped
        if(!Util.esNumero(jtfPrecioUnidad.getText()+evt.getKeyChar(),true))
            evt.consume();
    }//GEN-LAST:event_jtfPrecioUnidadKeyTyped
    private void jtfExistenciaKeyTyped(java.awt.event.KeyEvent evt) {//GEN-FIRST:event_jtfExistenciaKeyTyped
        if(!Util.esNumero(jtfExistencia.getText()+evt.getKeyChar(),false))
            evt.consume();
    }//GEN-LAST:event_jtfExistenciaKeyTyped
    private void jtfCantidadMinimaKeyTyped(java.awt.event.KeyEvent evt) {//GEN-FIRST:event_jtfCantidadMinimaKeyTyped
        if(!Util.esNumero(jtfCantidadMinima.getText()+evt.getKeyChar(),false))
            evt.consume();
    }//GEN-LAST:event_jtfCantidadMinimaKeyTyped
    private void jtbtnHabilitarBusquedaActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jtbtnHabilitarBusquedaActionPerformed
        if(jtbtnHabilitarBusqueda.isSelected()){
            jtbtnHabilitarBusqueda.setIcon(new ImageIcon(getClass().getResource("/Recursos/deshabilitar_busqueda.png")));
            jtbtnHabilitarBusqueda.setToolTipText("Deshabilitar Busqueda");
            jbtnBuscar.setVisible(true);
            jbtnCambiarDetalle.setVisible(true);
        }
        else{
            jtbtnHabilitarBusqueda.setIcon(new ImageIcon(getClass().getResource("/Recursos/habilitar_busqueda.png")));
            jtbtnHabilitarBusqueda.setToolTipText("Habilitar Busqueda");
            jbtnBuscar.setVisible(false);
            jbtnCambiarDetalle.setVisible(false);
        }
        //jpMarcasDistribucion.setVisible(!jtbtnHabilitarBusqueda.isSelected());
        jpInventario.setVisible(jtbtnHabilitarBusqueda.isSelected());
    }//GEN-LAST:event_jtbtnHabilitarBusquedaActionPerformed
    private void jbtnBuscarActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jbtnBuscarActionPerformed
        String columnas[]={"ID","Nombre","Detalle","Unidad Medida","Precio","Vencimiento","Existencia","Cantidad Mínima"};
        Util.CargarTabla(jtblProductos,"SELECT i.id_inventario,p.nombre,i.detalle,i.unidad_medida,i.precio_unidad_medida,"
                +"DATE_FORMAT(p.fecha_vencimiento,'%d/%m/%Y'),i.existencia,i.cantidad_minima FROM inventario i INNER JOIN producto p "
                +"ON i.id_producto=p.id_producto"+getFiltro(),columnas);
        Util.AlinearColumnas(jtblProductos,SwingConstants.CENTER);
        Util.OcultarColumna(jtblProductos,0);
        columnas=null;
    }//GEN-LAST:event_jbtnBuscarActionPerformed
    private void jbtnCambiarDetalleActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jbtnCambiarDetalleActionPerformed
        /*jpMarcasDistribucion.setVisible(!jpMarcasDistribucion.isVisible());
        jpInventario.setVisible(!jpInventario.isVisible());*/
    }//GEN-LAST:event_jbtnCambiarDetalleActionPerformed
    private void jtblProductosMouseClicked(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_jtblProductosMouseClicked
        if((evt.getClickCount()==2)&&(!evt.isConsumed())){
            if(jtblProductos.getSelectedRow()>-1){
                CargarInventario(jtblProductos.getSelectedRow());
                CargarDistribucionBodegas();
            }
            evt.consume();
        }
    }//GEN-LAST:event_jtblProductosMouseClicked
    private void jbtnModificarActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jbtnModificarActionPerformed
        BloquearControles(false);
        BloquearTexto(false);
        nuevo=false;
    }//GEN-LAST:event_jbtnModificarActionPerformed
    private void jbtnEliminarActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jbtnEliminarActionPerformed
        if(!jtfId.getText().equals("")){
            if(JOptionPane.showConfirmDialog(null,"¿Esta seguro de eliminar el producto del inventario y todo lo relacionado con el producto?","Eliminar Producto", JOptionPane.YES_NO_OPTION)==JOptionPane.OK_OPTION){
                Eliminar(jtfId.getText());
            }
        }
    }//GEN-LAST:event_jbtnEliminarActionPerformed
    private String[] getIdbodegasCantidades(){
        String ids[]={"",""};
        /*for(int i=0;i<jtblDistribucion.getRowCount();i++){
            if(ids[0].equals("")){
                ids[0]=jtblDistribucion.getValueAt(i,0).toString();
                ids[1]=jtblDistribucion.getValueAt(i,2).toString();
            }
            else{
                ids[0]+=","+jtblDistribucion.getValueAt(i,0).toString();
                ids[1]+=","+jtblDistribucion.getValueAt(i,2).toString();
            }
        }*/
        return ids;
    }
    private void CargarInventario(int fila){
        jtfId.setText(jtblProductos.getValueAt(fila,0).toString());
        jtfNombre.setText(jtblProductos.getValueAt(fila,1).toString());
        jtaDetalle.setText(jtblProductos.getValueAt(fila,2).toString());
        jtfUnidadMedida.setText(jtblProductos.getValueAt(fila,3).toString());
        jtfPrecioUnidad.setText(jtblProductos.getValueAt(fila,4).toString());
        ((JFormattedTextField)selector_fecha.getComponent(0)).setText(jtblProductos.getValueAt(fila,5).toString());
        jtfExistencia.setText(jtblProductos.getValueAt(fila,6).toString());
        jtfCantidadMinima.setText(jtblProductos.getValueAt(fila,7).toString());
        CargarMarcasProveedores(Integer.parseInt(jtfId.getText()));
    }
    private void CargarDistribucionBodegas(){
        /*if(!jtfId.getText().equals("")){
            String[] columnas={"bodega","cantidad"};
            JTable tabla=Conexion.ObtenerTabla("SELECT id_bodega,cantidad_bodega FROM detalledistribucion WHERE id_inventario="+jtfId.getText(), columnas);
            for(int i=0;i<tabla.getRowCount();i++){
                for(int j=0;j<jtblDistribucion.getRowCount();j++){
                    if(jtblDistribucion.getValueAt(j,0).toString().equals(tabla.getValueAt(i,0).toString())){
                        jtblDistribucion.setValueAt(tabla.getValueAt(i,1),j,2);
                        break;
                    }
                }
            }
            columnas=null;
            tabla=null;
        }*/
    }
    private void CargarMarcasProveedores(int id){
        String[] columnas={"id_marca","marca","id_proveedor","proveedor","cantidad"};
        JTable tabla=Conexion.ObtenerTabla("SELECT di.id_marca,m.descripcion,di.id_proveedor,p.nombre,di.cantidad FROM detalleinventario di INNER JOIN "
                +"marca m ON di.id_marca=m.id_marca INNER JOIN proveedor p ON di.id_proveedor=p.id_proveedor WHERE di.id_inventario="+id,columnas);
        /*for(int i=0;i<tabla.getRowCount();i++){
            Object dato[]={new Integer(tabla.getValueAt(i,0).toString()),tabla.getValueAt(i,1).toString(),
                new Integer(tabla.getValueAt(i,2).toString()),tabla.getValueAt(i,3).toString(),new Integer(tabla.getValueAt(i,4).toString())};
            ((DefaultTableModel)jtblMarcaProveedor.getModel()).addRow(dato);
        }*/
        columnas=null;
        tabla=null;
    }
    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JLabel jLabel1;
    private javax.swing.JLabel jLabel10;
    private javax.swing.JLabel jLabel11;
    private javax.swing.JLabel jLabel5;
    private javax.swing.JLabel jLabel6;
    private javax.swing.JLabel jLabel7;
    private javax.swing.JLabel jLabel8;
    private javax.swing.JLabel jLabel9;
    private javax.swing.JScrollPane jScrollPane3;
    private javax.swing.JScrollPane jScrollPane4;
    private javax.swing.JButton jbtnBuscar;
    private javax.swing.JButton jbtnCambiarDetalle;
    private javax.swing.JButton jbtnCancelar;
    private javax.swing.JButton jbtnEliminar;
    private javax.swing.JButton jbtnGuardar;
    private javax.swing.JButton jbtnModificar;
    private javax.swing.JButton jbtnNuevo;
    private javax.swing.JPanel jpAccion;
    private javax.swing.JPanel jpFechaVencimiento;
    private javax.swing.JPanel jpInventario;
    private javax.swing.JPanel jpProducto;
    private javax.swing.JTextArea jtaDetalle;
    private javax.swing.JTable jtblProductos;
    private javax.swing.JToggleButton jtbtnHabilitarBusqueda;
    private javax.swing.JTextField jtfCantidadMinima;
    private javax.swing.JTextField jtfExistencia;
    private javax.swing.JTextField jtfId;
    private javax.swing.JTextField jtfNombre;
    private javax.swing.JTextField jtfPrecioUnidad;
    private javax.swing.JTextField jtfUnidadMedida;
    // End of variables declaration//GEN-END:variables
}